package org.fastsyncer.plugin.impl.pool;

import java.util.HashMap;
import java.util.Map;

import org.fastsyncer.common.constant.ConnectorConstant;
import org.fastsyncer.common.entity.DatabaseConfig;
import org.fastsyncer.common.entity.Mapping;
import org.fastsyncer.common.util.UUIDUtil;
import org.fastsyncer.connector.framework.ConnectorFactory;
import org.fastsyncer.connector.framework.Database;
import org.fastsyncer.connector.util.DatabaseUtil;
import org.springframework.jdbc.core.JdbcTemplate;

public class DatabasePool {
    
    private static volatile DatabasePool instance = null;

    private DatabasePool(){
    }
    
    public static DatabasePool getInstance() {
        if (null == instance) {
            synchronized (DatabasePool.class) {
                if (null == instance) {
                    instance = new DatabasePool();
                }
            }   
        }
        return instance;
    }
    
    private Map<String, JdbcTemplate> pool = null;
    
    /**
     * 创建数据库连接,并加入连接池
     * @param mapping 数据源/目标源
     * @return 连接地址
     */
    public String create(Mapping mapping) {
        String connectorName = mapping.getConnector();
        if (!ConnectorConstant.isDatabaseConnector(connectorName)) {
            return null;
        }
        if (null == pool) {
            synchronized (this) {
                if (null == pool) {
                    pool = new HashMap<String, JdbcTemplate>();
                }
            }
        }
        // create connection into pool
        String id = UUIDUtil.getUUID();
        JdbcTemplate jdbc = pool.get(id);
        DatabaseConfig config = (DatabaseConfig) mapping.getConfig();
        if(null == jdbc){
            synchronized (this) {
                Database connector = ConnectorFactory.getInstance().getConnector(connectorName, Database.class);
                jdbc = connector.getJdbcTemplate(config);
                pool.put(id, jdbc);
            }
        }
        
        if(null == jdbc){
            return null;
        }
        
        // return connection uuid
        return id;
    }
    
    public JdbcTemplate get(String id) {
        return pool.get(id);
    }
    
    public void close(String id) {
        if (null != pool) {
            JdbcTemplate jdbc = pool.get(id);
            if(null != jdbc){
                // 释放连接
                DatabaseUtil.close(jdbc);
                pool.remove(id);
            }
        }
    }
    
}
